import React, { useCallback, useEffect, useState } from "react";
import SpuInfo from "./SpuInfo";
import { useSkuList, useSizeList, useSkuColumns } from "./hooks";
import { SimpleTable } from "@/views/components/SearchTable/index";
import PreviewMatch from "./PreviewMatch";
import { Button, message } from "antd";
import Style from "./index.module.less";
import { cloneDeep } from "lodash";
import { goodsSpuMatch } from "../service";
const TablePage = props => {
	const { selectedRows, isSkuType, onDrawerClose } = props;
	const selectedRow = selectedRows[0];
	const { spuId, spuImage, spuName } = selectedRow || {};

	const {
		tableKey,
		searchSimpleTableProps,
		skuList,
		skuColorList,
		skuSizeList,
		skuColorMatchList,
		setSkuColorMatchList,
		sizeSelectTableData,
		setSizeSelectTableData,
		matchedStoreSkuAllList,
		setMatchedStoreSkuAllList
	} = useSkuList({
		spuId,
		onDrawerClose
	});

	const { tableKey: sizeTableKey, searchSimpleTableProps: sizeSearchSimpleTableProps } = useSizeList({
		skuList,
		skuColorList,
		skuSizeList,
		sizeSelectTableData,
		setSizeSelectTableData,
		matchedStoreSkuAllList,
		setMatchedStoreSkuAllList
	});

	/******************************************** */
	const [previewVisible, setPreviewVisible] = useState(false);
	const [copyMatchData, setCopyMatchData] = useState(false); // 复制【颜色、尺码匹配后的源数据】，用于渲染预览的匹配表格弹窗

	const getMatchData = useCallback(() => {
		const __matchData = [];
		// 系统尺码匹配的供应商尺码
		const sizeMatchObj = {};
		// 尺码选择table的数据源
		sizeSelectTableData.forEach(sizeItem => {
			const key = sizeItem.sysSpecs;
			const storeIds = Object.keys(sizeItem).filter(e => !e.includes("Options") && e !== "sysSpecs");
			sizeMatchObj[key] = storeIds.map(storeId => {
				return {
					storeId, //677
					storeSize: sizeItem[storeId] //1.5m床（床单款）
				};
			});
		});

		// console.log("==========sizeMatchObj============");
		// console.log("skuList", skuList);
		// console.log("skuColorList", skuColorList);
		// console.log("skuSizeList", skuSizeList);
		// console.log("sizeMatchObj sizeSelectTableData", sizeMatchObj, sizeSelectTableData);
		// console.log("skuColorMatchList", skuColorMatchList);

		// 系统颜色列表
		skuColorList.forEach(colorItem => {
			// 系统颜色
			const sysColor = colorItem.colour;
			// 查找供应商颜色 ？
			const matchStoreFinder = skuColorMatchList.find(eee => eee.sys.colour === sysColor);
			let storeColor = matchStoreFinder?.store?.skuColor;

			//  已匹配的
			if (colorItem.supplierSkuId) {
				const matchSkuFinder = matchedStoreSkuAllList.find(e => e.goodsId == colorItem.supplierSkuId);
				if (matchSkuFinder) storeColor = matchSkuFinder?.color;
			}

			// 对应供应商颜色
			if (storeColor) {
				// 系统尺码列表
				skuSizeList.forEach(sizeItem => {
					// 系统尺码
					const sysSize = sizeItem.specs;

					// 系统尺码 + 系统颜色 = 系统sku
					const sysSkuFinder = skuList.find(eee => eee.colour == sysColor && eee.specs === sysSize);
					if (sysSkuFinder) {
						const { skuId: sysSkuId, image: sysSkuImage, skuName: sysSkuName } = sysSkuFinder;
						// 供应商尺码【多个供应商，有多个尺码数据，来自[尺码选择table]】
						const storeSizeList = sizeMatchObj[sysSize];
						(storeSizeList || []).forEach(({ storeId, storeSize }) => {
							let storeSkuId = null;
							let storeName = null;
							let storeSkuName = null;
							let storeSkuImage = null;
							// 已搜图的供应商sku列表下的items，查找供应商skuId
							skuList
								.filter(e => e.merge && e.found)
								.forEach(eee => {
									eee.items.forEach(eeeItem => {
										const eeeItemStoreGoodsName = eeeItem.goodsName;
										const eeeItemStoreName = eeeItem.storeName;
										const eeeItemStoreId = eeeItem.storeId;
										const eeeItemStoreSpec = eeeItem.spec;
										const eeeItemStoreSkuImage = eeeItem.skuImage;
										// spec列表，查找 ： storeSize + storeColor = 供应商SkuId
										const __storeSkuId = Object.keys(eeeItemStoreSpec).find(skuId => {
											const [__size, __color] = eeeItemStoreSpec[skuId];
											return __size === storeSize && __color === storeColor;
										});
										if (eeeItemStoreId == storeId && __storeSkuId) {
											storeSkuId = __storeSkuId;
											storeName = eeeItemStoreName;
											storeSkuName = eeeItemStoreGoodsName;
											storeSkuImage = eeeItemStoreSkuImage;
										}
									});
								});
							// 在搜图结果中未找到
							if (!storeSkuId) {
								//  已匹配的
								if (colorItem.supplierSkuId) {
									const matchSkuFinder = matchedStoreSkuAllList.find(e => e.color == storeColor && e.size == storeSize);
									if (matchSkuFinder) {
										storeSkuId = matchSkuFinder.goodsId;
										storeName = matchSkuFinder.storeName;
										storeSkuName = matchSkuFinder.goodsName;
										storeSkuImage = matchSkuFinder.goodsImage;
									}
								}
							}

							const o = {
								sysColor,
								sysSize,
								sysSkuId,
								sysSkuName,
								sysSkuImage,

								storeId,
								storeName,
								storeSkuName,
								storeColor,
								storeSize,
								storeSkuId,
								storeSkuImage
							};
							if (o.storeSkuId) __matchData.push(o);
						});
					}
				});
			} else {
				console.warn("not match color", storeColor, skuColorMatchList);
			}
		});

		console.warn("匹配数据setMatchData", __matchData);
		return __matchData;
	}, [skuList, skuColorList, skuSizeList, sizeSelectTableData, skuColorMatchList]);
	const preview = () => {
		const matchData = getMatchData();

		if (matchData.length == 0) {
			message.warning("未匹配商品");
			return;
		}
		const filterNotSize = matchData.filter(e => e.storeSize);

		if (filterNotSize.length == 0) {
			message.warning("至少匹配一个尺码");
			return;
		}

		setCopyMatchData(cloneDeep(filterNotSize));
		setPreviewVisible(true);
	};

	const onPreviewDelete = (record, index) => {
		setCopyMatchData(pre => {
			if (pre.length > 1) {
				pre.splice(index, 1);
			} else {
				message.warning("至少保留一组匹配关系！");
			}
			return cloneDeep(pre);
		});
	};

	const onPreviewOk = useCallback(() => {
		const API_DATA = {
			ids: [spuId],
			list: copyMatchData.map(record => {
				return {
					// 系统sku
					skuId: record.sysSkuId,
					// 供应商sku
					supplierId: record.storeId,
					supplierName: record.storeName,
					supplierSkuId: record.storeSkuId,
					supplierSkuImage: record.storeSkuImage,
					supplierSkuName: record.storeSkuName
				};
			}),
			type: 2 //关联类型 1：供应商 2：供应商商品
		};

		goodsSpuMatch(API_DATA)
			.then(res => {
				const { success, data, msg } = res;
				if (success) {
					message.success(msg || "匹配成功");
					onPreviewCancel();
					onDrawerClose();
				} else {
					message.warning(msg || "匹配失败");
				}
			})
			.catch(err => {
				console.error(err);
				message.warning("匹配接口请求失败");
			});
	}, [spuId, copyMatchData]);

	const onPreviewCancel = () => {
		setPreviewVisible(false);
	};
	return (
		<div className={"views-container " + Style.views_container}>
			<SpuInfo image={spuImage} spuName={spuName} />

			<SimpleTable key={tableKey} {...searchSimpleTableProps} className={"mb16 " + Style.views_container_table} />

			<SimpleTable key={sizeTableKey} {...sizeSearchSimpleTableProps} className={"mb16 " + Style.views_container_table} />

			<div className={"mb16 " + Style.views_container_button}>
				<Button type="primary" onClick={preview}>
					保存并预览
				</Button>
			</div>

			<PreviewMatch
				visible={previewVisible}
				onCancel={onPreviewCancel}
				onOk={onPreviewOk}
				onDelete={onPreviewDelete}
				dataSource={copyMatchData}
				zIndex={915}
			/>
		</div>
	);
};

export default React.memo(TablePage, () => {
	return true;
});
